<?php
// +----------------------------------------------------------------------
// | bbcThink
// +----------------------------------------------------------------------
// | Copyright (c) 2025 http://bbcweb.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: bbcweb <22745529@qq.com>
// +----------------------------------------------------------------------
function handleDate($time)
{
    if(date('Y',$time)<date('Y'))
    {
       return date('Y-m-d H:i',$time);
    }
    if(date('Y-m-d',$time)==date('Y-m-d'))
    {
        return date('H:i',$time);
    }
    return date('m-d H:i',$time);
}
function getUserLevName($lev)
{
    $lev_arr=[['id'=>1,'name'=>'普通用户'],['id'=>3,'name'=>'会员'],['id'=>5,'name'=>'VIP'],['id'=>10,'name'=>'连锁']];
    foreach ($lev_arr as $v)
    {
        if($lev==$v['id'])
        {
            return $v['name'];
        }
    }
    return '';
}
function logtype($type)
{
    $arr=['110'=>'报警','400'=>'删除','300'=>'修改','100'=>'登录','200'=>'新增','0'=>'添加'];
    return $arr[$type];
}

function formatPrice($price)
{
    //return number_format($price,2);
    if(strpos($price,'.')!==false)
    {
        $price_int=explode('.',$price)[0];
        $price_point=preg_replace('/\.?0+$/', '',explode('.',$price)[1]);
        $price_point=empty($price_point)?'':'.'.$price_point;
        $price=$price_int.$price_point;
    }
    return $price;
}

function buildQueryString($data) {
    $querystring = '';
    if (is_array($data)) {
        ksort($data);
        foreach ($data as $key => $val) {
            if (is_array($val)) {
                foreach ($val as $val2) {
                    $querystring .= urlencode($key).'='.urlencode($val2).'&';
                }
            } else {
                $querystring .= urlencode($key).'='.urlencode($val).'&';
            }
        }
        $querystring = substr($querystring, 0, -1); // Eliminate unnecessary &
    } else {
        $querystring = $data;
    }
    return $querystring;
}

function getWeek($date)
{
    $week_array=array("日","一","二","三","四","五","六");
    $week=date("w",$date);
    return $week_array[$week];
}
function toUpperCN($num,$len=0)
{
    $chnnum='';
    $unit=array('','十','百','千','万','十','百','千','亿','十','百','千','兆');
    $datacn=array('零','一','二','三','四','五','六','七','八','九');
    $sign=$num<0?'负':'';
    $num=abs($num);
    $numstr=strval($num);
    $alen=strlen($numstr);
    $pos=$alen-1;
    $lastunit=true;
    for($i=0;$i<$alen;$i++){
        $curidx=intval($numstr[$i]);
        $curunit=$unit[$pos];
        if($curidx>0){
            $chnnum.=$datacn[$curidx].$curunit;
            $lastunit=true;
        }
        elseif(!$lastunit){
            $chnnum.=$datacn[$curidx];
            $lastunit=true;
        }
        if($pos==4&&($lastunit||$curidx)){
            $chnnum.='万';
        }
        elseif($pos==8&&($lastunit||$curidx)){
            $chnnum.='亿';
        }
        $pos--;
    }
    if(!$chnnum){
        $chnnum.='零';
    }
    $chnnum=$sign.$chnnum;
    return$chnnum;
}
function amappoint($lng,$lat)
{
    $v_lng=str_replace('.','',$lng);
    $v_lat=str_replace('.','',$lat);
    $par = '/^\d*$/';
    if(!preg_match($par, $v_lng) || !preg_match($par,$v_lat))
    {
        $lng='';
        $lat='';
    }
    if($lat>$lng)
    {
        $tmp_poi=$lat;
        $lng=$lat;
        $lat=$tmp_poi;
    }
    return ['lng'=>$lng,'lat'=>$lat];
}
//获取日期时间戳
function getTimestamp($type=1)
{
    $timestamp=array(0,0);
    switch($type)
    {
        //今天
        case 1:
           $timestamp[0] =mktime(0,0,0,date('m'),date('d'),date('Y'));
           $timestamp[1] = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        break;
        //昨天
        case 2:
           $timestamp[0] = mktime(0,0,0,date('m'),date('d')-1,date('Y'));
           $timestamp[1] = mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
        break;
        //明天
        case 3:
           $timestamp[0] = mktime(0,0,0,date('m'),date('d')+1,date('Y'));
           $timestamp[1] = mktime(0,0,0,date('m'),date('d')+2,date('Y'))-1;
        break;
        //后天
        case 4:
           $timestamp[0] = mktime(0,0,0,date('m'),date('d')+2,date('Y'));
           $timestamp[1] = mktime(0,0,0,date('m'),date('d')+3,date('Y'))-1;
        break;
        //本周
        case 5:
           $timestamp[0] = mktime(0,0,0,date('m'),date('d')-date('w')+1,date('y'));
           $timestamp[1] =  mktime(23,59,59,date('m'),date('d')-date('w')+7,date('y'));
        break;
        //本月
        case 6:
            $day1=strtotime(date('Y-m').'-1');
            $timestamp[0] = $day1;
            $timestamp[1] = mktime(23,59,59,date('m'),date('t'),date('Y'));
        break;
        //上个月
        case 7:
           $timestamp[0] = strtotime(date('Y-m-01').' -1 month');
           $timestamp[1] = strtotime(date('Y-m-t',strtotime('-1 month')).' 23:59:59');
        break;
        //本季度
        case 8:
           $timestamp[0] = mktime(0,0,0,1,1,date('Y'));
           $timestamp[1] =  mktime(0,0,0,12,31,date('Y'));
        break;
        //上季度
        case 9:
           $timestamp[0] = mktime(0,0,0,1,1,date('Y'));
           $timestamp[1] =  mktime(0,0,0,12,31,date('Y'));
        break;
        //本年
        case 10:
           $timestamp[0] = mktime(0,0,0,1,1,date('Y'));
           $timestamp[1] =  mktime(0,0,0,12,31,date('Y'));
        break;
    }
    return $timestamp;
}
function object2array($array)
{
    if(is_object($array)) {  
        $array = (array)$array;  
     } if(is_array($array)) {  
        foreach($array as $key=>$value) {  
            $array[$key] = object2array($value);  
        }  
     }  
     return $array;
}

//提取正文中的图片
function getContentImg($str)
{
    $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
    preg_match_all($preg, $str, $allImg);
    return $allImg[1];
}
function formatdate($date,$isday=false)
{
    if(empty($date))
    {
        $date='';
    }
    else
    {
        //echo $date;
        //var_dump(is_null($date));
        if($date=='NULL' || $date==NULL || is_null($date))
        {
            return '';
        }
        else{
            if(!strpos($date,'-'))
            {
            if($isday)
            {
                $date=date('Y-m-d',$date);
            }
            else
            {
               
                $date=date('Y-m-d H:i:s',$date);
            }
            }
            else
            {
                return $date;
            }
        }
    }
    return $date;
}

function getOrderStatus($status)
{
    foreach (orderStatus() as $key=>$v)
    {
        if($key==$status)
        {
            return $v;
        }
    }
    return '';
}
function orderStatus()
{
    //0已取消，1未付款，2售后中，5已付款，6已发货，7已收货，8已评价，10已完成
    $status=['-1'=>'删除','0'=>'已关闭','1'=>'未付款','5'=>'已付款','6'=>'已发货','7'=>'已收货','8'=>'已评价','10'=>'已完成'];
    return $status;
}
function handleImg($obj)
{
    if(empty($obj))
    {
        return [];
    }
    $obj=urldecode($obj);
    if(false!==strpos($obj,']'))
    {
        $obj_arr=json_decode($obj,true);
    }
    else
    {
        $obj_arr=explode(',',$obj);
    }
    if(empty($obj_arr))
    {
        return [addimghost($obj)];
    }
    foreach ($obj_arr as &$v)
    {
        $v=addimghost($v);
    }
    return $obj_arr;
}

function numToRmb($num){
    $rmbNum = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
    $rmbUnit = ['分','角','元','拾','佰','仟','万','拾','佰','仟','亿','拾','佰','仟','万','拾','佰','仟'];
    //数字预处理
    $num = str_replace(',','',$num);
    if($num == '' || $num == 0){
        return '请输入一个大于0的金额，谢谢！';
    }else {
        $num = number_format($num, 2, '.', '')*100;
    }
    if (strlen(number_format($num, 0, '', ''))>18) {
        return '输入的金额不得超过千万亿！';
    }
    //开始数字转换人民币大写
    $out1 = 0;
    $numRmb = '';
    $unit = '';
    $rmb = '';
    for ($out1 = 0 ; $out1 < strlen(number_format($num, 0, '', '')) ; $out1++) {
        $numRmb = $rmbNum[substr(number_format($num, 0, '', ''), $out1, 1)];
        $unit = $rmbUnit[strlen(number_format($num, 0, '', ''))-$out1-1];
        $rmb = $rmb.$numRmb.$unit;
    }
    // 将大写人民币中的零进行调整
    $rmbStrlen = strlen($rmb);
    for ($out2=0; $out2 < $rmbStrlen; $out2=$out2+3) {
        $tempRmb = substr($rmb, $out2, 6);
        if ($tempRmb=='零元'||$tempRmb=='零万'||$tempRmb=='零亿') {
            $left = substr($rmb, 0, $out2);
            $right = substr($rmb, $out2+3);
            $rmb = $left.$right;
            $out2 = $out2 - 3;
            $rmbStrlen = $rmbStrlen - 3;
        }elseif ($tempRmb=='零拾'||$tempRmb=='零佰'||$tempRmb=='零仟') {
            $left = substr($rmb, 0, $out2+3);
            $right = substr($rmb, $out2+6);
            $rmb = $left.$right;
            $out2 = $out2 - 3;
            $rmbStrlen = $rmbStrlen - 3;
        }elseif ($tempRmb=='零分'||$tempRmb=='零角') {
            $left = substr($rmb, 0, $out2);
            $right = substr($rmb, $out2+6);
            $rmb = $left.$right;
            $out2 = $out2 - 6;
            $rmbStrlen = $rmbStrlen - 6;
        }
            
        if ($tempRmb=='零零') {
            $left = substr($rmb, 0, $out2);
            $right = substr($rmb, $out2+3);
            $rmb = $left.$right;
            $out2 = $out2 - 3;
            $rmbStrlen = $rmbStrlen - 3;
        }
        if(substr($rmb,strlen($rmb)-3)=='元') {
            $rmb = $rmb.'整';
       }
    }
    return $rmb;
}
/**
 * 生成随机数
 * @param $len
 * @return string
 */
function GetRandStr($len=4,$type=1) {
    $code = "1234567890";
    if($type==2)
    {
        $code="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    if($type==3)
    {
        $code=$code."ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    $count = strlen($code)-1;
    $arr = [];
    for($i=0;$i<$len;$i++){            
        $arr[$i] = $code[rand(0,$count)];            
    }
    $code = implode('',$arr);
    return $code;
}
function export_filename($filename,$data)
{
    header("Content-type:text/csv");
    header("Content-Disposition:attachment;filename=" . $filename);
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $data;
}
//是否手机号码格式
function isMobile($m){
   if(preg_match("/^1[3456789]\d{9}$/",$m)){
       return 1;
   }
   return 0;
}

function getOrderStatusName($status_id)
{
    $status=orderStatus();
    return $status[$status_id];
}
/**
*字符串转十六进制函数
*@pream string $str='abc';
*/
function strToHex($str){
    $hex="";
    for($i=0;$i<strlen($str);$i++)
    $hex.=dechex(ord($str[$i]));
    $hex=strtoupper($hex);
    return $hex;
    }
    /**
    *十六进制转字符串函数
    *@pream string $hex='616263';
    */
    function hexToStr($hex){
    $str="";
    for($i=0;$i<strlen($hex)-1;$i+=2)
    $str.=chr(hexdec($hex[$i].$hex[$i+1]));
    return $str;
    }
    function getHost()
    {
        return 'http://'.$_SERVER['HTTP_HOST'];
    }
    //生成token
    function make_token()
    {
        $str = md5(uniqid(md5(microtime(true)), true));
        $str = sha1($str); //加密
        return $str;
    }
function formatMoney($money)
{
    $money=number_format($money);
    return $money;
}
//优惠券类型
function getTicketCategory($category_id)
{
    $name=['','打折券','抵扣券','订单满减'];
    return $name[$category_id];
}
//补全网址
function addimghost($imagepath)
{
    if(strpos(strtolower($imagepath),'http')!== false)
    {
        return $imagepath;
    }
    return $imagepath='http://'.$_SERVER['HTTP_HOST'].$imagepath;
}

//生成订单编号
function createsn($param)
{
    $prefix = isset($param['prefix'])?$param['prefix']:'';
    $userid=isset($param['user_id'])?$param['user_id']:'';
    list($msec, $sec) = explode(' ', microtime());
    $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $prefix.$userid.date('YmdHis').substr($msectime,9,4);
}
function msectime()
{
    list($msec, $sec) = explode(' ', microtime());
    $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}
//验证规则
function checkedparams($data, $params)
{
    if(empty($params) || !is_array($data) || !is_array($params))
    {
        return '参数错误';
    }

    foreach ($params as $v)
    {
        if(empty($v['key_name']) || empty($v['error_msg']))
        {
            return '内部调用参数配置有误';
        }

        // 数据类型,默认字符串类型
        $data_type = empty($v['data_type']) ? 'string' : $v['data_type'];

        // 验证规则，默认isset
        $checked_type = isset($v['checked_type']) ? $v['checked_type'] : 'isset';
        switch($checked_type)
        {
            // 是否存在
            case 'isset' :
                if(!isset($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
                break;

            // 是否为空
            case 'empty' :
                if(empty($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
                break;

            // 是否存在于验证数组中
            case 'in' :
                if(empty($v['checked_data']) || !is_array($v['checked_data']))
                {
                    return '内部调用参数配置有误';
                }
                if(!isset($data[$v['key_name']]) || !in_array($data[$v['key_name']], $v['checked_data']))
                {
                    return $v['error_msg'];
                }
                break;

            // 是否为数组
            case 'is_array' :
                if(!isset($data[$v['key_name']]) || !is_array($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
                break;

            // 长度
            case 'length' :
                if(!isset($v['checked_data']))
                {
                    return '长度规则值未定义';
                }
                if(!is_string($v['checked_data']))
                {
                    return '内部调用参数配置有误';
                }
                if(!isset($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
                if($data_type == 'array')
                {
                    $length = count($data[$v['key_name']]);
                } else {
                    $length = mb_strlen($data[$v['key_name']], 'utf-8');
                }
                $rule = explode(',', $v['checked_data']);
                if(count($rule) == 1)
                {
                    if($length > intval($rule[0]))
                    {
                        return $v['error_msg'];
                    }
                } else {
                    if($length < intval($rule[0]) || $length > intval($rule[1]))
                    {
                        return $v['error_msg'];
                    }
                }
                break;

            // 自定义函数
            case 'fun' :
                if(empty($v['checked_data']) || !function_exists($v['checked_data']))
                {
                    return '验证函数为空或函数未定义';
                }
                $fun = $v['checked_data'];
                if(!isset($data[$v['key_name']]) || !$fun($data[$v['key_name']]))
                {
                    return $v['error_msg'];
                }
                break;

            // 最小
            case 'min' :
                if(!isset($v['checked_data']))
                {
                    return '验证最小值未定义';
                }
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] < $v['checked_data'])
                {
                    return $v['error_msg'];
                }
                break;

            // 最大
            case 'max' :
                if(!isset($v['checked_data']))
                {
                    return '验证最大值未定义';
                }
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] > $v['checked_data'])
                {
                    return $v['error_msg'];
                }
                break;

            // 相等
            case 'eq' :
                if(!isset($v['checked_data']))
                {
                    return '验证相等未定义';
                }
                if(!isset($data[$v['key_name']]) || $data[$v['key_name']] == $v['checked_data'])
                {
                    return $v['error_msg'];
                }
                break;
           
        }
    }
    return true;
}
//匹配中文字母数字=false
function isunchar($str)
{
    if (preg_match('/^[a-zA-Z0-9\x{4e00}-\x{9fa5}]/u', $str)) 
    {
        return false;
    }
    return true;
}
//判断只能是数字和字母
function ischarnum($str)
{
    if (preg_match('/[^A-Za-z0-9]/', $str)) 
    {
        return false;
    }
    return true;
}

function HttpRequestGet($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);
    return json_decode($res, true);
}
function HttpRequestPost($url, $data, $is_parsing = false)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_POST, true);

    $res = curl_exec($curl);
    if($is_parsing === true)
    {
        return json_decode($data, true);
    }
    curl_close($curl);
    return $res;
}
function jsonRes($res)
{
    if($res)
    {
        return jsonReturn(1,'操作成功');
    }
    else
    {
        return jsonReturn(0,'操作失败');
    }
}
function clearUnchar($html)
{
    $html = str_replace(array("\r\n", "\r", "\n",'"',"'"), "",$html);
    $html = strtolower($html);
    return $html;
}

/**
 * 返回json数据，用于接口
 * @param    integer    $code
 * @param    string     $msg
 * @param    array      $data
 * @param    string     $url
 * @param    integer    $httpCode
 * @param    array      $header
 * @param    array      $options
 * @return   json
 */
function jsonReturn($code = 1, $msg = "操作成功", $data = [], $url = '', $httpCode = 200, $header = [], $options = [])
{
    $res = ['code' => $code];
    $res['msg'] = $msg;
    $res['url'] = $url;
    if (is_object($data)) {
        $data = $data->toArray();
    }
    $res['data'] = $data;
    $response = \think\Response::create($res, "json", $httpCode, $header, $options);
    throw new \think\exception\HttpResponseException($response);
}
/**
 * 判断访客是否是蜘蛛
 */
function isRobot($except = '') {
    $ua = strtolower ( $_SERVER ['HTTP_USER_AGENT'] );
    $botchar = "/(baidu|google|spider|soso|yahoo|sohu-search|yodao|robozilla|AhrefsBot)/i";
    $except ? $botchar = str_replace ( $except . '|', '', $botchar ) : '';
    if (preg_match ( $botchar, $ua )) {
       return true;
    }
    return false;
 }
 /**
 * 判断是否是手机浏览器
 *  @return bool
 */
function isMobileExplore()
{
    if (isset($_SERVER['HTTP_VIA']) && stristr($_SERVER['HTTP_VIA'], "wap")) {
        return true;
    } elseif (isset($_SERVER['HTTP_ACCEPT']) && strpos(strtoupper($_SERVER['HTTP_ACCEPT']), "VND.WAP.WML")) {
        return true;
    } elseif (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE'])) {
        return true;
    } elseif (isset($_SERVER['HTTP_USER_AGENT']) && preg_match('/(blackberry|configuration\/cldc|hp |hp-|htc |htc_|htc-|iemobile|kindle|midp|mmp|motorola|mobile|nokia|opera mini|opera |Googlebot-Mobile|YahooSeeker\/M1A1-R2D2|android|iphone|ipod|mobi|palm|palmos|pocket|portalmmm|ppc;|smartphone|sonyericsson|sqh|spv|symbian|treo|up.browser|up.link|vodafone|windows ce|xda |xda_)/i', $_SERVER['HTTP_USER_AGENT'])) {
        return true;
    } else {
        return false;
    }
}

//构造输出
function DataReturn($msg = '', $code = 0, $data = '')
{    
    // 默认情况下，手动调用当前方法
    $result = ['msg'=>$msg, 'code'=>$code, 'data'=>$data];

    // 错误情况下，防止提示信息为空
    if($result['code'] != 0 && empty($result['msg']))
    {
        $result['msg'] = '操作失败';
    }
    //return $result;
    $response = \think\Response::create($result, "json");
    throw new \think\exception\HttpResponseException($response);
}
function getSysHost()
{
    return 'http://'.$_SERVER['HTTP_HOST'];
}

/**
 * 路径解析指定参数
 * @param   [string]            $key        [指定key]
 * @param   [mixed]             $default    [默认值]
 * @param   [string]            $path       [参数字符串 格式如： a/aa/b/bb/c/cc ]
 */
function PathToParams($key = null, $default = null, $path = '')
{
    $data = $_REQUEST;
    if(empty($path) && isset($_REQUEST['s']))
    {
        $path = $_REQUEST['s'];
    }
    if(empty($path))
    {
        $path = !empty($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : (empty($_SERVER['REDIRECT_URL']) ? (empty($_SERVER['REQUEST_URI']) ? (empty($_SERVER['PATH_TRANSLATED']) ? '' : $_SERVER['PATH_TRANSLATED']) : $_SERVER['REQUEST_URI']) : $_SERVER['REDIRECT_URL']);
    }

    if(!empty($path) && !array_key_exists($key, $data))
    {
        if(substr($path, 0, 1) == '/')
        {
            $path = mb_substr($path, 1, mb_strlen($path, 'utf-8')-1, 'utf-8');
        }
        $position = strrpos($path, '.');
        if($position !== false)
        {
            $path = mb_substr($path, 0, $position, 'utf-8');
        }
        $arr = explode('/', $path);

        
        $index = 0;
        foreach($arr as $k=>$v)
        {
            if($index != $k)
            {
                $data[$arr[$index]] = $v;
                $index = $k;
            }
        }
    }

    if($key !== null)
    {
        return array_key_exists($key, $data) ? $data[$key] : $default;
    }
    return $data;
}
/**
 * 获取当前系统所在根路径
 */
function GetDocumentRoot()
{
    // 当前所在的文档根目录
    if(!empty($_SERVER['DOCUMENT_ROOT']))
    {
        return $_SERVER['DOCUMENT_ROOT'];
    }

    // 处理iis服务器DOCUMENT_ROOT路径为空
    if(!empty($_SERVER['PHP_SELF']))
    {
        // 当前执行程序的绝对路径及文件名
        if(!empty($_SERVER['SCRIPT_FILENAME']))
        {
            return str_replace('\\', '/', substr($_SERVER['SCRIPT_FILENAME'], 0, 0 -strlen($_SERVER['PHP_SELF'])));
        }

        // 当前所在绝对路径
        if(!empty($_SERVER['PATH_TRANSLATED']))
        {
            return str_replace('\\', '/', substr(str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED']), 0, 0 -strlen($_SERVER['PHP_SELF'])));
        }
    }

    // 服务器root没有获取到默认使用系统root_path
    return (substr(ROOT_PATH, -1) == '/') ? substr(ROOT_PATH, 0, -1) : ROOT_PATH;
}
//请求get，支持本地文件
function RequestGet($value, $timeout = 10)
{
    // 远程
    if(substr($value, 0, 4) == 'http')
    {
        // 是否有curl模块
        if(function_exists('curl_init'))
        {
            return CurlGet($value, $timeout);
        }
        return file_get_contents($value);
    }

    // 本地文件
    return file_exists($value) ? file_get_contents($value) : '';
}
function download($url, $path = 'uploads/map/')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $resource = fopen($path . $filename, 'a');
    fwrite($resource, $file);
    fclose($resource);
    return  $path . $filename;
}
//curl模拟get请求
function CurlGet($url, $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
function getIp()
{
    $forwarded = request()->header("x-forwarded-for");
    if($forwarded){
        $ip = explode(',',$forwarded)[0];
    }else{
        $ip = request()->ip();
    }
    return $ip;
}
/**
 * 根据url地址解析顶级域名
 */
function GetUrlHost($url)
{
    // 地址解析
    $arr = parse_url(strtolower($url));
    $host = (count($arr) == 1) ? $arr['path'] : (empty($arr['host']) ? '' : $arr['host']);
    if(empty($host))
    {
        return $url;
    }

    // 是否存在斜杠
    if(stripos($host, '/') !== false)
    {
        $slash = explode('/', $host);
        $host = $slash[0];
    }

    // 查看是几级域名
    $data = explode('.', $host);
    $n = count($data);
    if(count($data) == 1)
    {
        return $host;
    }

    // 判断是否是双后缀
    $preg = '/[\w].+\.(com|net|org|gov|ac|bj|sh|tj|cq|he|sn|sx|nm|ln|jl|hl|js|zj|ah|fj|jx|sd|ha|hb|hn|gd|gx|hi|sc|gz|yn|gs|qh|nx|xj|tw|hk|mo|xz|edu|ge|dev|co)\.(cn|nz)$/';
    if(($n > 2) && preg_match($preg, $host))
    {
        // 双后缀取后3位
        $host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
    } else {
        // 非双后缀取后两位
        $host = $data[$n-2].'.'.$data[$n-1];
    }
    return $host;
}
//取得首字母
function getFirstCharter($str){
    if(empty($str)) {return '';}
    $fchar=ord($str[0]);
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str[0]);
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    $asc = ord($s[0])*256 + ord($s[1])-65536;
    if($asc>=-20319&&$asc<=-20284) return 'A';
    if($asc>=-20283&&$asc<=-19776 || $asc==-9743) return 'B';
    if($asc>=-19775&&$asc<=-19219) return 'C';
    if($asc>=-19218&&$asc<=-18711 || $asc==-9767) return 'D';
    if($asc>=-18710&&$asc<=-18527) return 'E';
    if($asc>=-18526&&$asc<=-18240) return 'F';
    if($asc>=-18239&&$asc<=-17923) return 'G';
    if($asc>=-17922&&$asc<=-17418) return 'H';
    if($asc>=-17417&&$asc<=-16475) return 'J';
    if($asc>=-16474&&$asc<=-16213) return 'K';
    if($asc>=-16212&&$asc<=-15641 || $asc==-7182 || $asc==-6928 ) return 'L';
    if($asc>=-15640&&$asc<=-15166) return 'M';
    if($asc>=-15165&&$asc<=-14923) return 'N';
    if($asc>=-14922&&$asc<=-14915) return 'O';
    if($asc>=-14914&&$asc<=-14631 || $asc==-6745) return 'P';
    if($asc>=-14630&&$asc<=-14150 || $asc==-7703) return 'Q';
    if($asc>=-14149&&$asc<=-14091) return 'R';
    if($asc>=-14090&&$asc<=-13319) return 'S';
    if($asc>=-13318&&$asc<=-12839) return 'T';
    if($asc>=-12838&&$asc<=-12557) return 'W';
    if($asc>=-12556&&$asc<=-11848) return 'X';
    if($asc>=-11847&&$asc<=-11056) return 'Y';
    if($asc>=-11055&&$asc<=-10247) return 'Z';
    return null;
}
function createNonceStr($length = 16) { //生成随机16个字符的字符串
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}
function curlpost($url , $data=array(),$header_data=array()){
    $ch = curl_init();
    if(!empty($header_data)){
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header_data);
        curl_setopt($ch, CURLOPT_HEADER, 0);//返回response头部信息
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    
    // POST数据
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function replace_specialChar($strParam){
$regex = "/\/|\～|\，|\。|\！|\？|\“|\”|\【|\】|\『|\』|\：|\；|\《|\》|\’|\‘|\ |\·|\~|\!|\@|\#|\\$|\%|\^|\&|\*|\(|\)|\_|\+|\{|\}|\:|\<|\>|\?|\[|\]|\,|\.|\/|\;|\'|\`|\-|\=|\\\|\|/";
    return preg_replace($regex,"",$strParam);
}
function logs($obj,$file="logs.txt")
{
    $fp = fopen($file,'a+');
    if(is_array($obj))
    {
        $obj = json_encode($obj,true);
    }
    fwrite($fp,"\r\n".date('Y-m-d H:i:s').' '.$obj);
    fclose($fp);
}
/**
     * 中文转拼音 (utf8版,gbk转utf8也可用)
     * @param string $str         utf8字符串
     * @param string $ret_format  返回格式 [all:全拼音|first:首字母|one:仅第一字符首字母]
     * @param string $placeholder 无法识别的字符占位符
     * @param string $allow_chars 允许的非中文字符
     * @return string             拼音字符串
     */
    function pinyin($str, $ret_format = 'all', $placeholder = '_', $allow_chars = '/[a-zA-Z\d ]/') {
        static $pinyins = null;
    
        if (null === $pinyins) {
            $data = file_get_contents(ROOT_PATH.'static/common/word');
            $rows = explode('|', $data);
    
            $pinyins = array();
            foreach($rows as $v) {
                list($py, $vals) = explode(':', $v);
                $chars = explode(',', $vals);
    
                foreach ($chars as $char) {
                    $pinyins[$char] = $py;
                }
            }
        }
    
        $str = trim($str);
        $len = mb_strlen($str, 'UTF-8');
        $rs = '';
        for ($i = 0; $i < $len; $i++) {
            $chr = mb_substr($str, $i, 1, 'UTF-8');
            $asc = ord($chr);
            if ($asc < 0x80) { // 0-127
                if (preg_match($allow_chars, $chr)) { // 用参数控制正则
                    $rs .= $chr; // 0-9 a-z A-Z 空格
                } else { // 其他字符用填充符代替
                    $rs .= $placeholder;
                }
            } else { // 128-255
                if (isset($pinyins[$chr])) {
                    $rs .= 'first' === $ret_format ? $pinyins[$chr][0] : ($pinyins[$chr] . '');
                } else {
                    $rs .= $placeholder;
                }
            }
    
            if ('one' === $ret_format && '' !== $rs) {
                return $rs[0];
            }
        }
    
        return rtrim($rs, ' ');
    }
function weekday()
{
    $week_1=mktime(0,0,0,date("m"),date("d")-date("w")+1,date("Y"));
    $week_2=mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
    return [$week_1,$week_2];
}
function weekname()
{
    $now_day = date('w',time());
    $w=['','星期一','星期二','星期三','星期四','星期五','星期六','星期日'];
    return $w[$now_day];
}
//判断图片色素值
function ChoiceImage($imgurl){
    //判断图片是否存在
    if(@fopen($imgurl,'r')){
        $total = 0;
        $rTotal = 0;
        $gTotal = 0;
        $bTotal = 0;
        $suffix = substr($imgurl, strrpos($imgurl, '.')+1);
        switch(strtolower($suffix))
        {   case "png":
              $i = imagecreatefrompng($imgurl);
            break;
            case "jpg":
                $i = imagecreatefromjpeg($imgurl);
            break;
        }
        
        for ($x=0;$x<imagesx($i);$x++) {
            for ($y=0;$y<imagesy($i);$y++) {
                $rgb = imagecolorat($i,$x,$y);
                $r=($rgb >> 16) & 0xFF;
                $g=($rgb >> 8) & 0xFF;
                $b=$rgb & 0xFF;
                $rTotal += $r;
                $gTotal += $g;
                $bTotal += $b;
                $total++;
            }
        }
        $rAverage = round($rTotal/$total);
        $gAverage = round($gTotal/$total);
        $bAverage = round($bTotal/$total);
        if($rAverage >= 250 || $gAverage >= 250 || $bAverage >= 250){
            return 0;
        }
        $rgbTotal = $rAverage + $gAverage + $bAverage;
//            pr_log('r: '. $rAverage . 'g: ' . $gAverage . 'b: ' .$bAverage,'ceshi110');
        if($rgbTotal >= 700 || $rgbTotal <= 10){
            return 0;
        }
        return $rgbTotal;
    }else{
        return 0;
    }
}
function arraySortByKey($array, $key, $asc = true)
{
    $result = array();
    foreach ( $array as $k => &$v ) {
        $values[$k] = isset($v[$key]) ? $v[$key] : '';
    }
    unset($v);
    $asc ? asort($values) : arsort($values);
    foreach ( $values as $k => $v ) {
        $result[$k] = $array[$k];
    }
    return $result;
}
//千位分割
function numbersplit($num)
{
    $num=str_replace('.00','',$num);
    if(strpos($num,'.'))
    {
        return number_format($num,2);
    }
    return number_format($num);
}
